package me.gavincook.mybatis.plugins;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.mybatis.generator.api.GeneratedXmlFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.XmlConstants;

/**
 * mybatis配置文件生成
 *
 * @author gavincook
 * @since 1.0.0
 */
public class MapperConfigurationPlugin extends PluginAdapter {

    private List<String> mapperFiles = new ArrayList<>();

    /**
     * 基础配置，指除了mappers的配置
     */
    private String baseConfig;
    /**
     * 目标文件夹，必须配置
     */
    private String targetProject;
    /**
     * 目标包名
     */
    private String targetPackage;

    @Override
    public boolean validate(List<String> warnings) {
        boolean valid = true;

        baseConfig = properties.getProperty("baseConfig");
        targetProject = properties.getProperty("targetProject");
        targetPackage = properties.getProperty("targetPackage");

        if (!stringHasValue(targetProject)) {
            warnings.add(getString("ValidationError.18", getClass().getSimpleName(), "targetProject"));
            valid = false;
        }

        return valid;
    }

    @Override
    public List<GeneratedXmlFile> contextGenerateAdditionalXmlFiles() {
        Document document = new Document(
            XmlConstants.MYBATIS3_MAPPER_CONFIG_PUBLIC_ID,
            XmlConstants.MYBATIS3_MAPPER_CONFIG_SYSTEM_ID);

        if (mapperFiles.isEmpty()) {
            return Collections.emptyList();
        }

        XmlElement root = new XmlElement("configuration");
        document.setRootElement(root);

        root.addElement(new TextElement("<!--"));
        root.addElement(new TextElement(
            "  This file is generated by MyBatis Generator."));
        root.addElement(new TextElement("-->"));

        root.addElement(new TextElement(baseConfig));

        XmlElement mappers = new XmlElement("mappers");
        root.addElement(mappers);

        XmlElement mapper;
        for (String mapperFile : mapperFiles) {
            mapper = new XmlElement("mapper"); //$NON-NLS-1$
            mapper.addAttribute(new Attribute("resource", mapperFile));
            mappers.addElement(mapper);
        }

        GeneratedXmlFile gxf = new GeneratedXmlFile(document, properties.getProperty("fileName", "MapperConfig.xml"),
            targetPackage,
            targetProject,
            false, context.getXmlFormatter());

        List<GeneratedXmlFile> answer = new ArrayList<>(1);
        answer.add(gxf);

        return answer;
    }


    @Override
    public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
        StringBuilder sb = new StringBuilder();
        sb.append(sqlMap.getTargetPackage());
        sb.append('.');
        String temp = sb.toString();
        sb.setLength(0);
        sb.append(temp.replace('.', '/'));
        sb.append(sqlMap.getFileName());
        mapperFiles.add(sb.toString());

        return true;
    }
}
